package com.itheima.aspect;


import com.itheima.aspect.annotation.OperLog;
import com.itheima.common.BaseContext;
import com.itheima.pojo.OperationLog;
import com.itheima.service.OperationLogService;
import org.apache.catalina.core.ApplicationContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.TimerTask;

@Aspect
@Component
public class OperationAspect {

    @Autowired
    OperationLogService operationLogService;

    //切入点表达式:标识哪些方法是切入点 需要进行增强的方法
    @Pointcut("@annotation(com.itheima.aspect.annotation.OperLog)")
    private void operatontionMethod(){

    }



    //切面:如何对哪些方法,进行哪些增强
    @Around("operatontionMethod()")
    //通知:具体的增强代码
    public Object operationLogHandle(ProceedingJoinPoint pjp){

        OperationLog operationLog = new OperationLog();

        //获取目标方法
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        //获取目标方法上的注解
        OperLog annotation = method.getAnnotation(OperLog.class);
        //获取注解属性
        String value = annotation.value();
        String username = annotation.username();

        operationLog.setOperation_action(value);

        //获取目标方法参数
        Object[] args = pjp.getArgs();


        Object result = null;

        try {
            //前置增强

             result = pjp.proceed(args);//执行目标方法

            //后置增强

        } catch (Throwable throwable) {
            throwable.printStackTrace();
            //异常增强

            new AsyncManager().execute(new TimerTask() {
                @Override
                public void run() {
                    operationLogService.save(operationLog);
                }
            });

        } finally {

            //返回后增强
            new AsyncManager().execute(new TimerTask() {
                @Override
                public void run() {
                    operationLogService.save(operationLog);
                }
            });


        }


        return result;
    }

}
